package com.andnnl.pool;

import java.util.Locale;
import java.util.ResourceBundle;

/**
 * 每隔一秒都会取最新的资源文件，资源文件立即生效
 */
public class ConfigFileHelper {
//    private static Logger logger = LoggerFactory.getLogger(ConfigFileHelper.class);
    private final static MyResourceBundleControl ctl = new MyResourceBundleControl();
    private String propertyFileName;
//	private ResourceBundle resourceBundle;

    public ConfigFileHelper(String propertyFileName) {
        this.propertyFileName = propertyFileName;
//		 resourceBundle = ResourceBundle.getBundle( propertyFileName );
        //取最新
//		resourceBundle= getBundle(propertyFileName);
        getBundle();
    }

    private ResourceBundle getBundle() {
        return ResourceBundle.getBundle(propertyFileName, Locale.getDefault(), ctl);
    }

    public String getString(String key) {
        if (key == null || key.equals("") || key.equals("null")) {
            return "";
        }
        String result = "";
        try {
            result = getBundle().getString(key);
            if (result == null)
                result = "";

            result = result.trim();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

	public String getString(String key,String defaultStr) {
		String result=getString(key);
		return "".equals(result)?defaultStr:result;
	}

    public int getInt(String key, int defaultValue) {
        int i = 0;
        String str = getString(key);
        if (str.equals(""))
            i = defaultValue;
        try {
            i = Integer.parseInt(str);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return i;
    }

    /**
     * 重载控制器
     */
    private static class MyResourceBundleControl extends ResourceBundle.Control {

        @Override
        public long getTimeToLive(String baseName, Locale locale) {
            return 1000;
        }

        @Override
        public boolean needsReload(String baseName, Locale locale,
                                   String format, ClassLoader loader, ResourceBundle bundle,
                                   long loadTime) {
            return true;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        ConfigFileHelper c = new ConfigFileHelper("config");
//		logger.info(c.getString("redis_host"));
//		logger.info(c.getInt("redis_port",6379));
//
//		logger.info(c.getString("memcache_host"));
//		logger.info(c.getInt("memcache_port",11211));

    }

}

